package com.ego.item.service.impl;

import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.item.mapper.CategoryMapper;
import com.ego.item.pojo.Category;
import com.ego.item.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional(readOnly = true)
    public List<Category> findListByPid(Long pid) {
        Map<String, Object> map = new HashMap<>();
        map.put("parent_id",pid);
        return categoryMapper.selectByMap(map);
    }

    @Override
    @Transactional
    public void save(Category category) {
//        categoryMapper.insert(category);

//        categoryMapper.insert(category);
//        throw new EgoException(ExceptionEnum.CATEGORY_SAVE_ERROR);

        try {
            categoryMapper.insert(category);
        }catch (Exception e){
            EgoException.error(log,ExceptionEnum.CATEGORY_SAVE_ERROR,e);
        }
    }

    @Override
    @Transactional
    public void updateById(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    @Transactional(readOnly = true)
    public Category findById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        categoryMapper.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Category> queryByBrandId(Long bid) {
        return categoryMapper.queryByBrandId(bid);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Category> findListByIdList(List<Long> categoryIdList) {
        return categoryMapper.selectBatchIds(categoryIdList);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Category> queryAllCategoryLevelByCid3(Long id) {
        List<Category> categoryList = new ArrayList<>();
        Category category = categoryMapper.selectById(id);
        while (category.getParentId() != 0){
            categoryList.add(category);
            category = categoryMapper.selectById(category.getParentId());
        }
        categoryList.add(category);
        return categoryList;
    }
}
